<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import axios from 'axios'
import { ElCard, ElTag, ElButton, ElEmpty, ElMessage } from 'element-plus'

// 定义参赛选手接口
interface Participant {
  playerId: number
  playerName: string
  score: number | null
  ranking: number | null
  isPromoted: number
  sdistance: number | null
  stimeValue: number | null
  stype: number | null
  sid: number
}

// 定义props
const props = defineProps({
  eventId: {
    type: Number,
    required: true
  },
  rankId: {
    type: Number,
    required: true
  }
})

// 响应式数据
const participants = ref<Participant[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const currentPage = ref(1)
const pageSize = ref(8) // 每页显示8条数据

// 计算当前页的数据
const paginatedParticipants = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return participants.value.slice(start, end)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(participants.value.length / pageSize.value)
})

// 获取参赛选手列表的方法
const fetchParticipants = async (eventId: number, rankId: number) => {
  try {
    loading.value = true
    error.value = null
    currentPage.value = 1 // 重置到第一页
    
    const token = localStorage.getItem('token')
    const response = await axios.get('http://localhost:8080/score/listByEventAndRank', {
      headers: {
        token: token || ''
      },
      params: {
        eventId: eventId,
        rankId: rankId
      }
    })
    
    if (response.data.success) {
      // 映射返回的数据字段到Participant接口
      participants.value = response.data.scores.map((item: any) => ({
        playerId: item.userId,
        playerName: item.userName,
        score: item.sscore,
        ranking: null, // API返回数据中没有排名信息
        isPromoted: item.isPromoted,
        sdistance: item.sdistance,
        stimeValue: item.stimeValue,
        stype: item.stype,
        sid: item.sid
      })) || []
    } else {
      error.value = '获取参赛选手列表失败'
    }
  } catch (err) {
    console.error('获取参赛选手列表出错:', err)
    error.value = '获取参赛选手列表时发生错误'
  } finally {
    loading.value = false
  }
}

// 添加晋级功能
const promoteParticipant = async (sid: number) => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.post('http://localhost:8080/score/promote', {}, {
      headers: {
        token: token || ''
      },
      params: {
        sId: sid
      }
    })
    
    if (response.data.success) {
      // 更新本地状态
      const participant = participants.value.find(p => p.sid === sid)
      if (participant) {
        participant.isPromoted = 1
      }
      ElMessage.success('晋级操作成功')
    } else {
      ElMessage.error(response.data.message || '晋级操作失败')
    }
  } catch (err) {
    console.error('晋级操作出错:', err)
    ElMessage.error('晋级操作时发生错误')
  }
}

// 添加取消晋级功能
const cancelPromoteParticipant = async (sid: number) => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.post(`http://localhost:8080/score/cancelPromote?sId=${sid}`, {}, {
      headers: {
        token: token || ''
      }
    })
    
    if (response.data.success) {
      // 更新本地状态
      const participant = participants.value.find(p => p.sid === sid)
      if (participant) {
        participant.isPromoted = 0
      }
      ElMessage.success('取消晋级操作成功')
    } else {
      ElMessage.error(response.data.message || '取消晋级操作失败')
    }
  } catch (err) {
    console.error('取消晋级操作出错:', err)
    ElMessage.error('取消晋级操作时发生错误')
  }
}

// 格式化时间显示 (sscore字段，单位是秒，需要转换为 H:mm:ss.SS格式)
const formatTimeScore = (seconds: number | null) => {
  if (seconds === null) return '未评分'
  
  // 计算小时、分钟、秒和毫秒
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  const millis = Math.round((seconds - Math.floor(seconds)) * 100)
  
  // 格式化显示
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}.${millis.toString().padStart(2, '0')}`
  } else {
    return `${minutes}:${secs.toString().padStart(2, '0')}.${millis.toString().padStart(2, '0')}`
  }
}

// 根据stype获取成绩显示
const getScoreDisplay = (participant: Participant) => {
  if (participant.stype === 1) {
    // 距离成绩，单位为米（浮点数）
    return participant.sdistance !== null ? `${participant.sdistance.toFixed(3)}米` : '未评分'
  } else if (participant.stype === 2) {
    // 得分成绩，单位是秒，需要转换为 H:mm:ss.SS格式
    return formatTimeScore(participant.score)
  } else if (participant.stype === 3) {
    // 时间成绩，单位为分（浮点数）
    return participant.stimeValue !== null ? `${participant.stimeValue.toFixed(2)}分` : '未评分'
  }
  return '未评分'
}

// 切换页面
const changePage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 返回成绩管理页面
const goBackToScoreManager = () => {
  const event = new CustomEvent('showGameEvent', {
    detail: { type: 'backToScoreManager' }
  });
  window.dispatchEvent(event);
}

// 监听props变化
watch([() => props.eventId, () => props.rankId], ([newEventId, newRankId]) => {
  if (newEventId && newRankId) {
    fetchParticipants(newEventId, newRankId)
  }
})

// 组件挂载时获取数据
onMounted(() => {
  if (props.eventId && props.rankId) {
    fetchParticipants(props.eventId, props.rankId)
  }
})

</script>

<template>
  <div class="score-order-container">
    <div class="header">
      <h2>参赛选手列表</h2>
      <el-button type="primary" @click="goBackToScoreManager" class="return-button">返回成绩管理</el-button>
    </div>
    
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>数据加载中...</p>
    </div>
    
    <div v-else-if="error" class="error">
      <el-empty :description="error" />
      <el-button type="primary" @click="fetchParticipants(props.eventId, props.rankId)">重新加载</el-button>
    </div>
    
    <div v-else>
      <div v-if="participants.length === 0" class="no-participants">
        <el-empty description="暂无参赛选手数据" />
      </div>
      
      <div v-else class="participants-list">
        <div 
          v-for="(participant, index) in paginatedParticipants" 
          :key="participant.playerId"
          class="item-content"
          :class="{ 'promoted': participant.isPromoted === 1 }"
        >
          <div class="player-rank">
            #{{ (currentPage - 1) * pageSize + index + 1 }}
          </div>
          <div class="player-name">
            {{ participant.playerName }}
          </div>
          <div class="score-value">
            {{ getScoreDisplay(participant) }}
          </div>
          <div 
            class="promotion-tag"
            :class="{ 'promoted-tag': participant.isPromoted === 1, 'not-promoted-tag': participant.isPromoted !== 1 }"
          >
            {{ participant.isPromoted === 1 ? '晋级' : '未晋级' }}
          </div>
          <div class="action-section">
            <el-button 
              type="primary" 
              size="default" 
              class="promotion-button"
              @click="participant.isPromoted === 1 ? cancelPromoteParticipant(participant.sid) : promoteParticipant(participant.sid)"
            >
              {{ participant.isPromoted === 1 ? '取消晋级' : '晋级' }}
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 分页控件 -->
      <div class="pagination" v-if="participants.length > 0">
        <el-button 
          :disabled="currentPage === 1" 
          @click="changePage(currentPage - 1)"
          plain
          class="page-button"
        >
          上一页
        </el-button>
        
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        
        <el-button 
          :disabled="currentPage === totalPages" 
          @click="changePage(currentPage + 1)"
          plain
          class="page-button"
        >
          下一页
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.score-order-container {
  width: 100%;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0;
}

.header h2 {
  color: #31B310;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.return-button {
  padding: 12px 24px;
  font-size: 16px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(49, 179, 16, 0.2);
  border-top: 4px solid #31B310;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error {
  text-align: center;
  padding: 20px;
}

.no-participants {
  padding: 50px 0;
}

.participants-list {
  display: flex;
  flex-direction: column;
  gap: 5px;
  margin-bottom: 20px;
}

.item-content {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 15px 20px;
  transition: all 0.3s ease;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-content:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.item-content.promoted {
  border-left: 4px solid #67c23a;
}

.player-rank {
  font-size: 20px;
  font-weight: bold;
  color: #31B310;
  width: 40px;
}

.player-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  flex: 1;
}

.score-value {
  font-size: 18px;
  font-weight: 500;
  color: #606266;
  min-width: 120px;
}

.promotion-tag {
  font-size: 14px;
  padding: 4px 12px;
  border-radius: 4px;
  font-weight: 500;
}

.promoted-tag {
  background-color: #67c23a;
  color: white;
}

.not-promoted-tag {
  background-color: #909399;
  color: white;
}

.action-section {
  display: flex;
  align-items: center;
}

.promotion-button {
  padding: 10px 20px;
  font-size: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.page-button {
  padding: 10px 20px;
  font-size: 16px;
}

.page-info {
  font-size: 16px;
  color: #606266;
  min-width: 150px;
  text-align: center;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .pagination {
    flex-wrap: wrap;
  }
  
  .item-content {
    flex-wrap: wrap;
  }
}
</style>